import router from '@/router';
import pinia from './store';
import useUserStore from '@/store/modules/user';
import settings from './settings';

import nprogress from 'nprogress';
import 'nprogress/nprogress.css';
nprogress.configure({ showSpinner: false });

let userStore = useUserStore(pinia);

// 访问路由之前触发的钩子
router.beforeEach(async (to: any, _from: any, next: any) => {
  document.title = `${settings.title} - ${to.meta.title}`;
  nprogress.start();
  let token = userStore.token;
  let username = userStore.username;
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' });
    } else {
      if (username) {
        next();
      } else {
        try {
          await userStore.userInfo();
          next({ ...to, replace: true });
        } catch {
          await userStore.userLogout();
          next({ path: '/login', query: { redirect: to.path } });
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next();
    } else {
      next({ path: '/login', query: { redirect: to.path } });
    }
  }
});

// eslint-disable-next-line @typescript-eslint/no-unused-vars
router.afterEach((_to: any, _from: any) => {
  nprogress.done();
});
